package org.cy.shixun.controller;


import org.cy.shixun.dto.UserUpdateDto;
import org.cy.shixun.entity.Users;
import org.cy.shixun.service.UsersService;
import org.cy.shixun.utils.JWTUtil;
import org.cy.shixun.utils.RedisUtil;
import org.cy.shixun.vo.R;
import org.cy.shixun.vo.UserReg;
import org.cy.shixun.vo.UserUpdate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


/**
 * 类名称：UsersController
 * 描述：用户登录
 *
 * @author: cy
 * @data: 2023/06/29
 */
@CrossOrigin
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private RedisUtil redisUtil;


    @GetMapping("Jwt")
    public R Jwt(HttpServletRequest request) {
        String tk = request.getHeader("tk");
        boolean exist = redisUtil.exist(tk);
        if(exist){
            return R.success("ok");
        }else{
            return R.error("请登录后再访问");
        }
    }

    /**
     * 登录
     *
     * @param users 用户
     * @return {@link String }
     */
    @PostMapping("/login")
    public String login(Users users) {
        int r = usersService.login(users);
        if (r == 0) {
            return "{\"r\":\"fail\",\"token\":\"\"}";
        } else {
            //产生token
            Map<String, String> payload = new HashMap<>();
            payload.put("account", users.getAccount());
            String token = JWTUtil.getToken(payload);
            System.out.println("生成的token是：" + token);
            //将token缓存到redis数据库
            redisUtil.setString(token, users.getAccount());
            return "{\"r\":\"index\",\"token\":\"" + token + "\"}";
        }
    }

    //用户名验证是否可用
    @GetMapping("/validate")
    public String validate(String act) {
        return usersService.validate(act);
    }

    /**
     * 注册
     *
     * @param userReg 用户注册
     * @return {@link String }
     */
    @GetMapping("/reg")
    public String reg(UserReg userReg) {
        String msg = usersService.reg(userReg);
        return msg;
    }

    /**
     * 修改用户密码
     *
     * @param userUpdate 用户更新
     * @return {@link String }
     */
    @PostMapping("/update")
    public R update(@RequestBody UserUpdate userUpdate, HttpServletRequest request) {
        //获取用户名
        String token = request.getHeader("tk");
        String account = redisUtil.getString(token);
        if (account == null) {
            return R.error("用户不存在");
        }
        UserUpdateDto userUpdateDto = new UserUpdateDto();
        BeanUtils.copyProperties(userUpdate, userUpdateDto);
        userUpdateDto.setAccount(account);
        return usersService.update(userUpdateDto);
    }


}
